"""6.1.0 ajout d'un base supplier payment

Revision ID: c4b03f713cae
Revises: ba72c4430612
Create Date: 2021-03-18 11:07:23.185516

"""

# revision identifiers, used by Alembic.
revision = "c4b03f713cae"
down_revision = "ba72c4430612"

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql


def pre_migrate_data():
    # On copie les colonnes que l'on migre vers la base table
    op.execute(
        """
        insert into base_supplier_payment
        (id, created_at, updated_at, date, amount, supplier_invoice_id, exported, type_)
        select
        id, created_at, updated_at, date, amount, supplier_invoice_id, exported, 'supplier_payment'
        from supplier_payment;
        """
    )


def update_database_structure():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint(
        "fk_supplier_payment_supplier_invoice_id",
        "supplier_payment",
        type_="foreignkey",
    )
    op.create_foreign_key(
        op.f("fk_supplier_payment_id"),
        "supplier_payment",
        "base_supplier_payment",
        ["id"],
        ["id"],
        ondelete="cascade",
    )
    op.drop_column("supplier_payment", "created_at")
    op.drop_column("supplier_payment", "amount")
    op.drop_column("supplier_payment", "updated_at")
    op.drop_column("supplier_payment", "supplier_invoice_id")
    op.drop_column("supplier_payment", "date")
    op.drop_column("supplier_payment", "exported")
    # ### end Alembic commands ###


def migrate_datas():
    from alembic.context import get_bind
    from zope.sqlalchemy import mark_changed
    from caerp_base.models.base import DBSESSION

    session = DBSESSION()
    conn = get_bind()

    mark_changed(session)
    session.flush()


def upgrade():
    pre_migrate_data()
    update_database_structure()
    migrate_datas()


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    pass
